//
//  HRZSearchTagManager.m
//  EMarket
//
//  Created by 石头 on 2018/5/31.
//  Copyright © 2018 好日子. All rights reserved.
//

#import "HRZSearchTagManager.h"

#import <FMDB.h>

@interface HRZSearchTagManager ()
{
    FMDatabase *_db;
}

@end

@implementation HRZSearchTagManager


+ (instancetype)shareDefaultManager {
    static HRZSearchTagManager *_mgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _mgr = [[HRZSearchTagManager alloc] init];
        [_mgr initBase];
    });
    return _mgr;
}

- (void)initBase{
    
}

- (void)initialize
{
    // 1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"searchModel.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    
    // 2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_searchModel (id integer PRIMARY KEY, searchModel blob NOT NULL, searchModel_idstr varchar NOT NULL);"];
    
    [_db close];
}


- (NSDictionary *)statusesWithParams:(NSDictionary *)params
{
    [_db open];
    
    // 根据请求参数生成对应的查询SQL语句
    NSString *sql = nil;
    if (params[@"category"]) {
        sql = [NSString stringWithFormat:@"SELECT * FROM t_searchModel WHERE searchModel_idstr = %@ ;", params[@"category"]];
    }else{
        sql = @"SELECT * FROM t_searchModel;";
    }
    // 执行SQL
    FMResultSet *set = [_db executeQuery:sql];
    while (set.next) {
        NSData *statusData = [set objectForColumn:@"searchModel"];
        NSDictionary *status = [NSKeyedUnarchiver unarchiveObjectWithData:statusData];
        [_db close];
        return status;
    }
    [_db close];
    return @{};
}


- (void)saveStatuses:(NSDictionary *)statuses andParam:(NSDictionary *)ParamDict
{
    [_db open];
    
    NSString *category = ParamDict[@"category"];
    
    [[HRZSearchTagManager shareDefaultManager] delect:ParamDict[@"category"]];
    
    NSData *statusData = [NSKeyedArchiver archivedDataWithRootObject:statuses];
    [_db executeUpdateWithFormat:@"INSERT INTO t_searchModel(searchModel, searchModel_idstr) VALUES (%@, %@);", statusData, category];
    
    [_db close];
}

- (BOOL)delect:(NSString *)searchModel_idstr
{
    [_db open];
    
    BOOL success = YES ;
    NSString * newSql = [NSString stringWithFormat:@"DELETE  FROM t_searchModel WHERE searchModel_idstr = ?"];
    BOOL isCan =  [_db executeUpdate:newSql,searchModel_idstr];
    if (!isCan) {
        success = NO;
    }
    
    [_db close];
    return success;
}

@end
